package com.shycloud.mido.music.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.music.domain.MisMusicCollection;
import com.shycloud.mido.music.domain.MisMusicLibrary;
import com.shycloud.mido.music.domain.MisUserBuyCollection;
import com.shycloud.mido.music.domain.MisUserCollection;
import com.shycloud.mido.music.dto.MisMusicCollectionAddDTO;
import com.shycloud.mido.music.dto.MisMusicCollectionDTO;
import com.shycloud.mido.music.mapper.MisMusicCollectionMapper;
import com.shycloud.mido.music.mapper.MisUserBuyCollectionMapper;
import com.shycloud.mido.music.service.*;
import com.shycloud.mido.music.service.impl.MisUserBuyCollectionService;
import com.shycloud.mido.music.util.CommonString;
import com.shycloud.mido.music.vo.MyCollectionVO;
import com.shycloud.mido.music.vo.UserCollectionVO;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.bean.BeanUtil;

import java.util.*;

/**
 * 曲集模块 Controller
 *
 * @author nianhua.jiang
 * @description
 * @date 2020/5/6
 */
@RestController
@AllArgsConstructor
@ApiOperation(value = "曲集模块")
@RequestMapping("/musicCollection")
public class MusicCollectionController {

	private final MisMusicCollectionMapper mapper;
	/** 曲集 service */
	private final MisMusicCollectionService collectionService;
	/** 曲库 service */
	private final MisMusicLibraryService libraryService;
	/** 自定义曲集 service */
	private final MisMyCollectionService misMyCollectionService;
	/** 收藏曲目 service */
	private final MisUserMusicService userMusicService;
	/** minio 交互类 */
	private final MinioTemplate minioTemplate;
	/** 收藏曲集 service */
	private final MisUserCollectionService userCollectionService;
	/** 购买曲集 service */
	private final MisUserBuyCollectionService buyCollectionService;
	/** 购买曲集业务 mapper */
	private final MisUserBuyCollectionMapper buyCollectionMapper;
	/** redis */
	private final RedisTemplate redisTemplate;

	/**
	 * 添加/编辑曲集
	 *
	 * @param misMusicCollection
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/6 10:48
	 */
	@PostMapping("/addMusicCollection")
	@ApiOperation(value = "添加/编辑曲集")
	public R addMusicCollection(@RequestBody MisMusicCollectionAddDTO misMusicCollection) {

		Set musicLibrary = redisTemplate.keys("musicLibrary*");
		if (!musicLibrary.isEmpty()) {
			redisTemplate.delete(musicLibrary);
		}
		return new R(collectionService.saveCollection(misMusicCollection));
	}

	@GetMapping("/updateMusicFileStatus")
	public R updateMusicFileStatus(Integer collectionId) {
		return new R(mapper.updateMusicFileStatus(collectionId));
	}

	@GetMapping("/updateMusicDelFlag")
	public R updateMusicDelFlag(Integer collectionId) {
		return new R(mapper.updateMusicDelFlag(collectionId));
	}

	@GetMapping("/getCollectionNameList")
	@ApiOperation("获取曲集名称列表")
	public R getCollectionNameList() {

		//查询所有有效的曲集信息 - 0730追加 【显示启用的数据】
		List<MisMusicCollection> list = collectionService.list(new QueryWrapper<MisMusicCollection>()
				.eq(MisMusicCollection.COL_DEL_FLAG, CommonString.DELETE_FLG)
				.and(x -> x.eq(MisMusicCollection.COL_COLLECTION_STATUS, CommonConstants.STATUS_NORMAL))
				.orderByAsc(MisMusicCollection.COL_SORT));
		return new R(list);

	}

	/**
	 * 删除曲集
	 *
	 * @param collectionId 曲集ID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/7 10:49
	 */
	@GetMapping("delMusicCollection")
	@ApiOperation("删除曲集")
	public R delMusicCollection(Integer collectionId) {
		Set musicLibrary = redisTemplate.keys("musicLibrary*");
		if (!musicLibrary.isEmpty()) {
			redisTemplate.delete(musicLibrary);
		}
		return new R(collectionService.deleteMusicConllection(collectionId));
	}

	/**
	 * 分页获取曲集（后台管理端）
	 *
	 * @param libraryId      曲库ID
	 * @param collectionName 曲集名称
	 * @param size           每页显示条数
	 * @param current        当前页
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/6 15:04
	 */
	@GetMapping("/getMusicCollectionManagement")
	@ApiOperation("分页获取曲集")
	public R getMusicCollectionManagement(String status, Integer libraryId, String collectionName, Integer collectionId, Integer size,
			Integer current) {

		//分页参数
		Page page = new Page(current, size);
		//获取曲集分页数据
		return new R(collectionService.getMusicConllection(page, libraryId, collectionName, collectionId, status));

	}

	/**
	 * 分页获取曲集(移动端)
	 *
	 * @param libraryId 曲库ID
	 * @param size      每页显示条数
	 * @param current   当前页
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/6 15:04
	 */
	@GetMapping("/getMusicCollection")
	@ApiOperation("分页获取曲集")
	public R getMusicCollection(Integer libraryId, Integer size, Integer current, Integer chargeType) {

		//分页参数
		Page page = new Page(current, size);
		//获取曲集分页数据
		return new R(collectionService.getMusicConllectionMobile(page, libraryId, chargeType));

	}


	/**
	 * 获取所有曲系列表
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/7 9:39
	 */
	@GetMapping("getLibraryNameList")
	@ApiOperation("获取所有曲系列表")
	public R getLibraryNameList() {
		return new R(libraryService.list(new QueryWrapper<MisMusicLibrary>().orderByAsc(MisMusicLibrary.COL_SORT)));
	}

	/**
	 * 判断曲集名称是否重复
	 *
	 * @param collectionName 曲集名称
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/6 11:17
	 */
	@GetMapping("checkCollectionName")
	@ApiOperation("判断曲集名称是否重复")
	public R checkCollectionName(String collectionName) {

		QueryWrapper<MisMusicCollection> queryWrapper = new QueryWrapper<>();
		//曲集名称
		queryWrapper.eq(MisMusicCollection.COL_NAME, collectionName);
		//逻辑删除
		queryWrapper.eq(MisMusicCollection.COL_DEL_FLAG, CommonString.DELETE_FLG);
		//检索曲集表
		List<MisMusicCollection> misMusicCollections = collectionService.list(queryWrapper);
		//如果存在曲集名称
		if (misMusicCollections.size() > 0) {
			//返回错误信息
			return new R(CommonConstants.FAIL, "曲集已存在", false);
		}
		return new R(CommonConstants.SUCCESS, "曲集可使用", true);
	}

	/**
	 * 上传封面图片
	 *
	 * @param img
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/7 14:39
	 */
	@PostMapping("uploadImg")
	@ApiOperation(value = "上传封面图片")
	public R uploadImg(@RequestParam("img") MultipartFile img) {

		//提取后缀
		//提取图片名称
		String fileName = img.getOriginalFilename().replaceAll(" ", "");
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

		String uuid = UUID.randomUUID().toString();
		//提取图片名称
		String imgName = uuid.replace("-", "") + "." + suffix;
		//初始化map结果集
		Map<String, String> resultMap = new HashMap<>(4);
		//名称
		resultMap.put("name", imgName);
		try {
			//上传操作
			minioTemplate.uploadFile(img.getInputStream(), imgName, "cover-img");
			resultMap.put("url", "http://cover.img.joymido.com/" + imgName);
		} catch (Exception e) {
			return R.builder().code(CommonConstants.FAIL).msg(e.getLocalizedMessage()).build();
		}
		return R.builder().data(resultMap).build();

	}

	/**
	 * 收藏/取消收藏曲集(取消收藏采用真删逻辑)
	 *
	 * @param map flg          【0:收藏，1:取消收藏】
	 * @param map collectionId 曲集ID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/8 10:47
	 */
	@ApiOperation("收藏/取消收藏曲集")
	@PostMapping("saveUserCollection")
	public R saveUserCollection(@RequestBody Map<String, Object> map) {

		//曲集ID集合
		List<Integer> collectionIdArr = (List<Integer>) map.get("collectionId");
		//del_flg
		String flg = (String) map.get("flg");

		//获取登录信息
		String userId = SecurityUtils.getMember().getId();

		for (Integer collectionId : collectionIdArr) {

			//收藏
			if ("0".equals(flg)) {

				//重复收藏报错
				MisUserCollection userCollection = userCollectionService.getOne(new QueryWrapper<MisUserCollection>()
						.eq(MisUserCollection.COL_TYPE, "1")
						.and(x -> x.eq(MisUserCollection.COL_MEMBER_ID, userId))
						.and(y -> y.eq(MisUserCollection.COL_DEL_FLAG, CommonConstants.STATUS_NORMAL))
						.and(z -> z.eq(MisUserCollection.COL_COLLECTION_ID, collectionId)));

				if (userCollection != null) {
					return new R(CommonConstants.FAIL, "无法重复收藏", false);
				}

				MisUserCollection misUserCollection = new MisUserCollection();
				//用户ID
				misUserCollection.setMemberId(userId);
				//曲目ID
				misUserCollection.setCollectionId(collectionId);
				//类型( 1-收藏 2-下载）
				misUserCollection.setType(CommonString.USER_MUSIC_TYPE_SAVE);
				//逻辑删除（0：未删除，1：已删除）
				misUserCollection.setDelFlag(CommonString.DELETE_FLG);
				//创建时间
				misUserCollection.setCreateTime(new Date());
				//创建人
				misUserCollection.setCreateUser(SecurityUtils.getMember().getId());
				//更新时间
				misUserCollection.setUpdateTime(new Date());
				//更新人
				misUserCollection.setUpdateUser(SecurityUtils.getMember().getId());
				userCollectionService.save(misUserCollection);
			}
			//取消收藏
			else if ("1".equals(flg)) {
				QueryWrapper<MisUserCollection> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq(MisUserCollection.COL_COLLECTION_ID, collectionId);
				queryWrapper.eq(MisUserCollection.COL_MEMBER_ID, userId);
				userCollectionService.remove(queryWrapper);
			}
			//flg参数不正确
			else {
				return new R<>(CommonConstants.FAIL, "flg参数不正确", false);
			}
		}
		return new R(CommonConstants.SUCCESS, "操作成功", true);
	}

	/**
	 * 获取我收藏的曲集信息
	 *
	 * @param current
	 * @param size
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/16 15:23
	 */
	@GetMapping("getUserCollection")
	@ApiOperation("获取我收藏的曲集信息")
	public R getUserCollection(Integer current, Integer size) {

		//获取member_id
		String memberId = SecurityUtils.getMember().getId();
		//分页参数
		Page page = new Page(current, size);

		return new R(userCollectionService.getUserCollection(memberId, page));
	}

	/**
	 * 获取我收藏的有声图书列表
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/16 16:29
	 */
	@GetMapping("getMySoundBook")
	@ApiOperation("获取我收藏的有声图书列表")
	public R getMySoundBook(Page page) {
		return new R(collectionService.getMySoundBook(page));
	}

	/**
	 * 获取定制曲集
	 *
	 * @param current
	 * @param size
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/7/6 17:05
	 */
	@GetMapping("getCustomCollection")
	@ApiOperation("获取定制曲集")
	public R getCustomCollection(Integer current, Integer size) {

		//获取会员ID
		String memberId = SecurityUtils.getMember().getId();

		//分页参数
		Page page = new Page(current, size);

		return new R(userCollectionService.getUserCollectionIsCustom(memberId, page));

	}

	@GetMapping("getCollectionDetail")
	@ApiOperation("获取曲集详情")
	public R getCollectionDetail(Integer id) {
		MisMusicCollectionDTO dto = new MisMusicCollectionDTO();
		MisMusicCollection entity = collectionService.getById(id);
		BeanUtil.copyProperties(entity, dto);
		List<Integer> libraryIds = mapper.selectLibraryIdsById(id);
		dto.setLibraryIds(libraryIds);

		return new R(dto);
	}

	/**
	 * 根据collectionId获取有效曲集详情（后台管理用）
	 *
	 * @param collectionId
	 * @return
	 */
	@GetMapping("getById")
	@ApiOperation("根据collectionId获取曲集详情（后台管理用）")
	public R getById(Integer collectionId) {
		//根据曲集ID获取曲集实体数据
		MisMusicCollection misMusicCollection = collectionService.getValidCollectionById(collectionId);

		return misMusicCollection == null ?
				new R<>(CommonConstants.FAIL,
						"未找到对应曲集，请确定曲集是否有效", false) : new R(misMusicCollection);
	}

	@GetMapping("/changeVIPStatus")
	@ApiOperation("批量改变曲集VIP状态")
	public R changeVIPStatus(String status, Integer collectionId) {
		return new R<>(mapper.changeVIPStatus(status, collectionId));
	}

	//====================================== 小程序获取曲集列表 （单曲收藏，自建，收藏） =====================================//

	/**
	 * 小程序下发作业获取曲集列表 单曲收藏/收藏曲集/自建曲集
	 *
	 * @param searchWord
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/11/26 14:54
	 **/
	@GetMapping("getUserCollectionByMini")
	public R getUserCollectionByMini(String searchWord) {

		String memberId = SecurityUtils.getMember().getId();

		List<MyCollectionVO> resultList = new ArrayList<>();

		//获取曲目收藏列表
		Integer count = userMusicService.getUserMusicCount(memberId);
		MyCollectionVO userMusic = new MyCollectionVO();
		userMusic.setMusicCount(count);
		userMusic.setId(-1);
		userMusic.setType("0");
		userMusic.setName("单曲收藏");
		//搜索自建曲集
		List<MyCollectionVO> myCollection = misMyCollectionService.getMyCollectionByMini(searchWord, memberId);
		//搜索收藏曲集
		List<MyCollectionVO> collectionByMini = userCollectionService.getUserCollectionByMini(searchWord, memberId);

		if (StringUtils.isEmpty(searchWord)) {
			resultList.add(userMusic);
		}

		resultList.addAll(myCollection);
		resultList.addAll(collectionByMini);

		return new R(resultList);
	}

	@GetMapping("getCollByMusicIdFeign")
	public MisMusicCollection getCollByMusicId(Integer musicId) {
		return mapper.getCollByMusicId(musicId);
	}

	@ApiOperation("获取我的书架")
	@GetMapping("getBuyCollectionPage")
	public R getBuyCollectionPage(Integer current, Integer size, String memberId) {
		return new R(buyCollectionService.getBuyCollectionPage(new Page(current, size), memberId));
	}

	@ApiOperation("首页初次进入显示已购买的曲集")
	@GetMapping("getByCollectionListHomePageShow")
	public R getByCollectionListHomePageShow(String memberId) {
		return new R(buyCollectionMapper.getByCollectionListHomePageShow(memberId));
	}

	@GetMapping("updateIsShowByMemberId")
	public R updateIsShowByMemberId(String memberId) {
		return new R(buyCollectionMapper.updateIsShowByMemberId(memberId));
	}

}
